﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Openlab.Tools.CodeGender.Funtions
{
    public class GetEntitiesFunc : Function
    {
        string entityClass;
        string getEntitiesFuncName;
        string entityCacheName;
        Column idColumn;

        string paramEntities, paramIds;

        public GetEntitiesFunc(string entityClass
            , string getEntitiesFuncName, string entityCacheName, Column idColumn)
            : base(
                string.Format("Get{0}", entityClass.ToPlural())
                , string.Format("static List<{0}>", entityClass)
                , null)
        {
            this.entityClass = entityClass;
            this.getEntitiesFuncName = getEntitiesFuncName;
            this.entityCacheName = entityCacheName;
            this.idColumn = idColumn;
            string idType = idColumn.CSTypeName;

            paramEntities = entityClass.ToFirstLower().ToPlural();
            paramIds = idColumn.Name.ToFirstLower().ToPlural();

            Parameters = new List<FunctionParameter>();
            Parameters.Add(new FunctionParameter(paramIds, string.Format("{0}[]", idType)));
            Parameters.Add(new FunctionParameter(string.Format("{0}Cacheable", paramEntities), "bool"));
        }


        public override string Body
        {
            get {
                string template = @"
Dictionary<[IdType], [EntityClass]> [ParamEntities] = new Dictionary<[IdType], [EntityClass]>();
return [EntityCache].GetEntities([ParamEntityIds], ref [ParamEntities], [ParamEntities]Cacheable,
    new GetEntitiesFromDatabaseDelegate<[IdType], [EntityClass]>(DataAccess.[GetEntitiesFunc]));";

                template = template.Replace("[ParamEntityIds]", paramIds);
                template = template.Replace("[ParamEntities]", paramEntities);
                template = template.Replace("[IdType]", idColumn.CSTypeName);
                template = template.Replace("[EntityClass]", entityClass);
                template = template.Replace("[EntityCache]", entityCacheName);
                template = template.Replace("[GetEntitiesFunc]", getEntitiesFuncName);

                return template;
            }
        }
    }
}
